import Taro from "@tarojs/taro";

// 是否是 json 字符串
export function isJsonString(str: string) {
  try {
    if (typeof JSON.parse(str) == "object") {
      return true;
    }
  } catch (e) {
    return false;
  }
  return false;
}

//缓存数据
export const setCache = (key: string, value: any) => {
  let params: any = value;
  if (typeof value == "object") {
    params = JSON.stringify(value);
  }
  return Taro.setStorageSync(key, params);
};

//读取缓存
export const getCache = (key: string) => {
  let result = Taro.getStorageSync(key);
  if (result) {
    if (isJsonString(result)) {
      result = JSON.parse(result);
    }
  } else {
    return null;
  }
  return result;
};


//删除缓存
export const removeCache = (key: string) => {
  return Taro.removeStorageSync(key);
};


export default {
  setCache,
  getCache,
  removeCache
};
